<template>
  <div class="videoBox" @click="playVideo">
    <div class="name">{{ name }}</div>
    <video ref="videoRef" :width="props.width" :height="props.height" controls disablePictureInPicture></video>
  </div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import flvjs from "flv.js";
import { ElNotification } from 'element-plus';
/** @api */
interface Props {
  width: string,
  height: string,
  path?: string, // rtps路径
  name?: string, // rtps路径
}
// 组件传参
const props = withDefaults(defineProps<Props>(), {});
const emits = defineEmits(['callback']);
/** @数据 */
const videoRef = ref<HTMLVideoElement>()
/** flv播放器 */
let flvPlayer: flvjs.Player | undefined = undefined;
/** 是否播放 */
// const tfPlay: boolean = false;
/** @生命周期 */
onBeforeUnmount(() => {
  destroyFlv();
})
/** @方法 */
/** 播放video */
const playVideo = () => {
  // if (flvPlayer) {
  //   // 获取当前播放状态
  //   const playerState = flvPlayer.getState();
  //   if (playerState === 'PLAYING') {
  //     console.log('播放状态');
  //   } else if (playerState === 'PAUSED') {
  //     console.log('暂停状态');
  //   } else {
  //     console.log('其他状态');
  //   }
  // }

  // if (!flvPlayer) {

  //   emits("callback");
  // }
}
/** 创建flv */
const createdFlv = () => {
  if (videoRef.value && flvjs.isSupported() && props.path) {
    flvPlayer = flvjs.createPlayer({
      type: 'flv',
      isLive: true,
      url: `${props.path}.live.flv`,
    })
    flvPlayer.attachMediaElement(videoRef.value);
    // 静音播放
    flvPlayer.volume = 0; // 将音量设置为 0
    flvPlayer.load();
    flvPlayer.play();
  } else {
    ElNotification.warning('连接视频失败，请检查视频网络是否正常')
  }
}
/** 更换视频流 */
const changeRtsp = () => {
  if (flvPlayer && videoRef.value) {
    flvPlayer.unload(); //取消数据流加载
    flvPlayer = flvjs.createPlayer({
      type: 'flv',
      isLive: true,
      url: `${props.path}.live.flv`,
    })
    flvPlayer.attachMediaElement(videoRef.value);
    flvPlayer.load();
    flvPlayer.play();
  } else {
    createdFlv()
  }
}
// 暂停播放
// const pause = () => {
//   if (flvPlayer) {
//     flvPlayer.pause(); //暂停播放数据流
//     flvPlayer.unload(); //取消数据流加载
//     // this.state.flvPlayer.detachMediaElement(); //将播放实例从节点中取出
//     // this.state.flvPlayer.destroy(); //销毁播放实例
//   }
// }
/** 销毁flv */
const destroyFlv = () => {
  if (flvPlayer) {
    flvPlayer.pause();
    flvPlayer.unload();
    flvPlayer.detachMediaElement();
    flvPlayer.destroy();
  }
}
/** @侦听器 */
watch(() => props.path, () => {
  changeRtsp()
})
/** @公共方法 */
</script>
<style lang="scss" scoped>
.videoBox {
  border-radius: 6px;
  border-bottom-right-radius: 17px;
  overflow: hidden;
  position: relative;

  .name {
    position: absolute;
    z-index: 1;
    width: 100%;
    text-align: center;
    display: none
  }

  & .name {
    display: inline-block;
  }
}
</style>